package common

import (
	"context"
	"device-admin/config/redis"
	"device-admin/internal/app/grpc/protoc/robotc"
	"device-admin/internal/app/grpc/service/pubsub"
	"device-admin/internal/define"
	"strconv"
	"time"

	"192.168.1.75/go-pkg/logx"
	"google.golang.org/protobuf/proto"
)

// GetRobotConfig
func GetRobotConfig(robotID string, key string) string {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	val, _ := redis.NewDB().HGet(
		ctx,
		define.RedisDDRConfig+robotID,
		"PPOAC_Params.OA_OBS_RADIUS",
	).Result()
	return val
}

// ConfigItemReq 设备配置请求
func RobotConfigReq(robotID string, configItemTypes []string) {
	defer func() {
		if err := recover(); err != nil {
			logx.Error(context.Background(), "getConfigItem", logx.Any("err", err))
		}
	}()
	reqConfigOperational := &robotc.ReqConfigOperational{
		Type: robotc.EConfigItemOptType_eConfigOptTypeGetData, // 读取数据
	}
	for _, itemType := range configItemTypes {
		reqConfigOperational.Data = append(reqConfigOperational.Data, &robotc.ConfigData{
			Type: robotc.EConfigItemType_eConfigTypeCore,
			Data: &robotc.ConfigItem{
				Key: []byte(itemType),
			},
		})
	}
	bodyType := string(reqConfigOperational.ProtoReflect().Descriptor().FullName())
	bodyContent, err := proto.Marshal(reqConfigOperational)
	if err != nil {
		logx.Error(context.Background(), "getConfigItem", logx.Err(err))
	}
	pubsub.LocalMsgPublish(robotID, "95", "wildmsg", bodyType, bodyContent, "")
}

// GetLowBatteryTh 获取低电量阈值
func GetLowBatteryTh(robotID string) int {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	// 获取低电量阈值
	lowBatteryTh, _ := redis.NewDB().HGet(
		ctx,
		define.RedisDDRConfig+robotID,
		"MR_Params.RECHARGING_BATT_LO_PER",
	).Result()
	lowBatteryThInt, _ := strconv.Atoi(lowBatteryTh)
	lowBatteryThInt = lowBatteryThInt / 100
	if lowBatteryThInt <= 0 { // 默认10%
		lowBatteryThInt = 10
	}
	return lowBatteryThInt
}
